package com.taobao.machinesystem.config;

import com.taobao.machinesystem.entity.SysUser;
import com.taobao.machinesystem.service.SysPermissionService;
import com.taobao.machinesystem.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Slf4j
//自定义的UserRealm  需要继承 AuthorizingRealm类
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService userService;

    @Autowired
    private SysPermissionService sysPermissionService;

    /**
     * 重写AuthorizingRealm类的两个方法
     * 该两个方法为重载
     * PrincipalCollection 为授权
     * AuthenticationToken 为认证
     */
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) {
        log.info("执行了=》授权doGetAuthorizationInfo");
        //给用户授予某个权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //将user:add的权限赋予给访问改页面的用户
        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        SysUser currentUser = (SysUser) subject.getPrincipal();//拿到User对象
        //获取权限标志
        List<String> authorizationList = sysPermissionService.findByAuthorization(currentUser.getId());
        //设置当前用户的权限
        info.addStringPermissions(authorizationList);
//        info.addStringPermission(currentUser.getPerms());
//       不能再return null 了;
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("执行了=》认证doGetAuthorizationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //链接真实的数据库
        SysUser user = userService.queryUserByLogin(userToken.getUsername());
        if (user == null) {
            //用户名不存在，没有这个人
            return null;//UnknownAccountException
        }
        //密码认证，shroi做，防止密码泄露      “第一个参数，将用户的信息放进去，这样使用Subject就可以获取到当前登录的用户信息了”
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
